package com.horoscope.astrology.zodiac.signs.free.network.task

import com.horoscope.astrology.zodiac.signs.free.bean.BaseBean
import com.horoscope.astrology.zodiac.signs.free.network.ApiCenter
import com.horoscope.astrology.zodiac.signs.free.network.HttpEngine
import com.horoscope.astrology.zodiac.signs.free.network.NetworkListener
import com.horoscope.astrology.zodiac.signs.free.utils.Logger
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers

open class BaseTask<T : BaseBean>(private val listener: NetworkListener<T>?) {

    private var httpEngine: HttpEngine? = null

    private fun getHttpEngine(): HttpEngine {
        if (null == httpEngine) {
            httpEngine = HttpEngine()
        }
        return httpEngine!!
    }

    fun setApiAndCallBack(observable: Observable<T>) {
        observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(BaseObserver(listener))
    }

    fun getApiCenter(): ApiCenter {
        return getHttpEngine().getApiCenter()
    }

    open inner class BaseObserver(private val listener: NetworkListener<T>?) : DisposableObserver<T>() {

        private lateinit var temp: T

        override fun onComplete() {
            if (RESULT_STATUS_OK == temp.status) {
                listener?.onSuccess(temp)
            } else {
                listener?.onFailed(temp)
            }
        }

        override fun onNext(t: T) {
            temp = t
        }

        override fun onError(e: Throwable) {
            listener?.onError(e.message)
            Logger.debug(TAG, e.toString())
        }

    }

    companion object {

        private val TAG = BaseTask::class.java.simpleName
        private const val RESULT_STATUS_OK = "OK"

    }
}